#include "mystdio.h"

//打开文件
myfile* my_fopen(const char* pathname, const char* mode)
{
    //标志符判断
    int flag = 0;
    if(strcmp(mode, "r") == 0)
    {
        flag |= (O_RDONLY);
    }
    else if(strcmp(mode, "w") == 0)
    {
        flag |= (O_WRONLY|O_CREAT|O_TRUNC);
    }
    else if(strcmp(mode, "a") == 0)
    {
        flag |= (O_WRONLY|O_CREAT|O_APPEND);
    }
    else 
    {
        return NULL;//打开方式错误
    }
    //调用系统接口，得到返回值fd
    int fd = 0;
    if(flag & O_WRONLY)
    {
        umask(0);
        fd = open(pathname, flag, 0666);//打开文件
    }
    else
    {
        fd = open(pathname, flag);
    }
    //file类型的实例开在堆上
    myfile* fp = (myfile*)malloc(sizeof(myfile));
    if(fp == NULL) return NULL;
    fp->fileno = fd;
    fp->pos = 0;
    fp->cap = SIZE;
    fp->flush = line_flush;//先用行刷新测试
    return fp;
}

//刷新缓冲区
void my_flush(myfile* fp)
{
    if(fp->pos == 0) return;
    write(fp->fileno, fp->outbuffer, fp->pos);//调用系统接口，写入内核
    fp->pos = 0;
}

//写入文件
void my_fwrite(myfile* fp, const char* str, int size)
{
    memcpy(fp->outbuffer+fp->pos, str, size);//输入的字符串拷贝到文件的字符串
    fp->pos += size;//加字符串的个数

    if((fp->flush & line_flush) && fp->outbuffer[fp->pos-1] == '\n')//行缓冲,斜杠n也算一个字符
    {
        my_flush(fp);
    }
    else if((fp->flush & full_flush) && fp->pos == fp->cap)//全缓冲
    {
        my_flush(fp);
    }
}

//关闭文件
void my_fclose(myfile* fp)
{
    my_flush(fp);//退出前要刷新
    close(fp->fileno);//调用系统接口，关闭文件
    free(fp);//释放资源
}